const app = getApp();
const weixinId = app.globalData.weixinId;
const cookie = app.globalData.cookie;

Page({
  data: {
    userName: weixinId,
    formShow: false, //表单弹出层
    currentDate: '', //当前时间
    weekDaysArray: [], //头部日期
    timeSlots: [
      '08:00',
      '08:30',
      '09:00',
      '09:30',
      '10:00',
      '10:30',
      '11:00',
      '11:30',
      '12:00',
      '12:30',
      '13:00',
      '13:30',
      '14:00',
      '14:30',
      '15:00',
      '15:30',
      '16:00',
      '16:30',
      '17:00',
      '17:30',
      '18:00',
      '18:30',
      '19:00',
      '19:30',
      '20:00',
      '20:30',
      '21:00',
      '21:30',
    ],
    timeLog: [
      ' ',
      ' ',
      ' ',
      ' ',
      ' ',
      ' ',
      ' ',
      ' ',
      ' ',
      ' ',
      ' ',
      ' ',
      ' ',
      ' ',
      ' ',
      ' ',
      ' ',
      ' ',
      ' ',
      ' ',
      ' ',
      ' ',
      ' ',
      ' ',
      ' ',
      ' ',
      ' ',
      ' ',
    ],
    rooms: [],
    value1: 0, //选项默认
    // 会议室选择器
    meetingCount: 0,
    roomShow: false,
    room: '请选择会议室',
    isCheckRoom: false,
    calendar: [], //在日历中显示已经预约了的
    checkedDay: '', //月日
    inputTheme: '', //参赛主题
    inputNumber: '', //参赛人数
    timeType: '', //是开始还是结束
    beginTime: '请选择开始时间',
    endTime: '请选择结束时间',

    //时间选择器
    startShow: false,
    minHour: 8,
    maxHour: 21,
    filter(type, options) {
      if (type === 'minute') {
        return options.filter((option) => option % 30 === 0);
      }
      return options;
    },
    physicalScreenHeight: 0,
  },
  // 函数
  onLoad: function () {
    this.updateCurrentDate(); // 更新当前日期
    this.getRoomIm(); //获取房间信息
    // this.showMeetings();
    try {
      const res = wx.getSystemInfoSync();
      const screenWidth = res.screenWidth; // 屏幕宽度（逻辑像素）
      // rpx=screenWidth/750 px
      const physicalScreenHeight =
        wx.getSystemInfoSync().windowHeight - (100 * screenWidth) / 750;

      // 使用 setData 更新页面数据
      this.setData({
        physicalScreenHeight: physicalScreenHeight,
      });
      console.log('屏幕高度（逻辑像素）：' + physicalScreenHeight + 'rpx');
    } catch (e) {
      console.error('获取系统信息失败：', e);
    }
  },
  //会议室
  showRoom() {
    this.setData({ roomShow: ~this.data.roomShow });
  },
  getRoom(e) {
    this.setData({
      room: e.detail.value.text,
      isCheckRoom: true,
      RoomID: e.detail.value.RoomID,
      calendar: []
    });
    console.log('获取会议室', e.detail.value.RoomID);
    this.getMeetings(e.detail.value.RoomID);//获取已预约的会议室的信息
    this.showRoom();
  },
  //获取已预约的会议室的信息
  getMeetings(RoomID) {
    // 使用 setData 方法将 calendar 和weekDaysArray 设置为空数组
    this.setData({
      calendar: []
    });
    this.updateCurrentDate();
    /*
    // if (this.data.room !== "请选择会议室") {
    //   // 获取当前的 weekDaysArray
    //   let currentWeekDaysArray = this.data.weekDaysArray;

      // 遍历 weekDaysArray 中的每个对象
      // for (let i = 0; i < currentWeekDaysArray.length; i++) {
      //   // 直接修改每个对象的 hasRes 属性
      //   currentWeekDaysArray[i].hasRes = false;
      //   currentWeekDaysArray[i].Theme=[];

      //   console.log("清除信息", currentWeekDaysArray[i].hasRes);
      // }
      // console.log("清除信息", currentWeekDaysArray);
      // // 更新 page 的数据
      // this.setData({
      //   weekDaysArray: currentWeekDaysArray
      // });
    // }
    */
    const that = this;
    wx.request({
      //https://itlab.ctgu.edu.cn/labapi
      url:
        `https://itlab.ctgu.edu.cn/labapi/MeetingManage/GetWeekReservation?WeiXinID=${weixinId}&RoomID=${RoomID}`,
      method: 'GET',
      header: {
        'content-type': 'application/json',
        'Cookie': cookie
      },
      success(res) {
        const data = res.data.DataInfo.DataList;
        var meetingCount = 0;
        console.log("获取已预约的会议室的信息", data);

        for (let i = 0; i < data.length; i++) {
          const item = data[i];
          for (let j = 0; j <= 6; j++) {
            const dayKey = `D${j}`;

            if (item[dayKey] && item[dayKey].Theme !== "") {
              console.log("获取成功", item[dayKey].Theme !== "");
              meetingCount += 1;
              const startTime = item[dayKey].BeginTime;
              const startDateTime = new Date(startTime);
              // 提取年份
              const year = startDateTime.getFullYear();

              // 提取月份和日期
              const month = String(startDateTime.getMonth() + 1).padStart(2, '0'); // 月份从 0 开始，所以需要加 1
              const day = String(startDateTime.getDate()).padStart(2, '0');

              // // 提取小时和分钟
              // const startHours = String(startDateTime.getHours()).padStart(2, '0');
              // const startMinutes = String(startDateTime.getMinutes()).padStart(2, '0');

              // 组合成所需的格式
              const startDateString = `${year}-${month}-${day}`;
              // const startTimeString = `${startHours}:${startMinutes}`;

              // 获取在 startTimeString 和 endTimeString 之间的 timeSlots 的下标
              const [startTime2, endTime] = item[dayKey].MeetingTime.split('-').map(time => time.trim());
              console.log(startDateString, "开始时间：", startTime2);
              // 获取在 startTimeString 和 endTimeString 之间的 timeSlots 的下标
              const indices = that.getTimeSlotIndices(startTime2, endTime);
              const index = that.data.room.indexOf('【'); // 查找第一个 "【" 的位置
              const meetingRoom = that.data.room.substring(0, index); // 截取从开头到 "【" 之前的部分
              // 要求将每一组数据分解后储存进calendar
              that.setData({
                calendar: [
                  ...that.data.calendar,
                  {
                    year,
                    date: `${month}-${day}`,
                    startTime: startTime2,
                    endTime: endTime,
                    UserName: item[dayKey].UserName,
                    RoomName: meetingRoom,
                    indices: indices,
                    Difference: indices[1] - indices[0],
                    theme: item[dayKey].Theme
                  },
                ],
                meetingCount: meetingCount
              });
            }
          }
        }
        console.log(that.data.calendar);
        that.showMeetings();
      }
    })
  },
  //显示预约信息日历
  showMeetings() {
    let t = 0;
    if (this.data.calendar.length)
      for (let i = 0; i < this.data.meetingCount; i++) {
        const j = this.data.weekDaysArray.findIndex(
          (day) => day.date === this.data.calendar[i].date
        );
        if (j !== -1) {
          console.log(this.data.calendar[i].theme, "显示预约信息日历", j);
          this.data.weekDaysArray[j].hasRes = true;
          const userName = this.data.calendar[i].UserName;
          const indices = this.data.calendar[i].indices;
          const theme = this.data.calendar[i].theme;
          if (indices[0] < 26 && indices.length > 2) {
            //个数
            this.data.weekDaysArray[j].lengthIn[indices[0] + 1] = indices.length;
            this.data.weekDaysArray[j].UserName[indices[0] + 1] = userName;
            this.data.weekDaysArray[j].Theme[indices[0] + 1] = theme;
            this.data.weekDaysArray[j].startIndex[indices[0] + 1] = indices[0] + 1;
            console.log('???!!', userName, this.data.weekDaysArray[j].startIndex[indices[0] + 1]);
          } else {
            this.data.weekDaysArray[j].lengthIn[indices[0]] = indices.length;
            this.data.weekDaysArray[j].UserName[indices[0]] = userName;

            this.data.weekDaysArray[j].Theme[indices[0]] = theme;
            this.data.weekDaysArray[j].startIndex[indices[0]] = indices[0];
            console.log("有进来的吗");
          }
          t++;

          for (let n = 0; n < indices.length; n++) {
            //第 个是存在
            this.data.weekDaysArray[j].calendarIndex[indices[n]] = 1; // 将索引 i 添加到 calendarIndex 数组中
            if (indices[n] < 28) {
              if (this.data.weekDaysArray[j].startIndex[indices[n] + 1] === 0)
                this.data.weekDaysArray[j].startIndex[indices[n] + 1] = 30;
            }
            //   // 使用 filter() 方法过滤出 number 不为 null 的元素
            //   const nonNullElements = this.data.weekDaysArray[j].UserName.filter(item => item.data !== null);
            //   // 使用 map() 方法获取这些元素的下标
            //   const indexesOfNonNull = nonNullElements.map((item, index) => this.data.weekDaysArray[j].UserName.indexOf(item));
            //   //循环indexesOfNonNull
            //   for (let m = 0; m < indexesOfNonNull.length; m++)
            //     if (indexesOfNonNull[m] == indices[n] + 1) {
            //       console.log(indices[n], "不为 null 的元素", indexesOfNonNull);
            //       this.data.weekDaysArray[j].startIndex[indices[n] + 1] = indexesOfNonNull[m];
            //     }
            //     else
            //       this.data.weekDaysArray[j].startIndex[indices[n] + 1] = 1;
            // }
          }
          this.setData({
            weekDaysArray: this.data.weekDaysArray,
          });
          console.log('已经预约了的房间', this.data.calendar);
        }
      }
  },
  //获取可预约房间信息
  getRoomIm() {
    const params = {
      Cookie: cookie,//必填
      // RoomNum: '',//非必填：支持模糊查询
    };
    // 保存 this 的引用
    const that = this;
    wx.request({
      //https://itlab.ctgu.edu.cn/labapi
      url:
        `https://itlab.ctgu.edu.cn/labapi/MeetingManage/SelectRoom?WeiXinID=${weixinId}`,
      method: 'GET',
      header: {
        'content-type': 'application/json',
        'Cookie': cookie
      },
      success(res) {
        console.log('会议室原始', res.data);
        const DataList = res.data.DataInfo.DataList;

        // 初始化 displays 数组
        const displays = [];

        // 遍历 DataList 并填充 displays 数组
        for (let i = 0; i < DataList.length; i++) {
          let display = '';
          switch (DataList[i].DisplayCata) {
            case 1:
              display = '投影';
              break;
            case 2:
              display = '电视';
              break;
            case 3:
              display = 'LED';
              break;
            default:
              display = '无';
              break;
          }
          displays[i] = display;
        }

        // 构建选项列表
        const options = DataList.map((room, index) => ({
          text: `${room.RoomName}【${room.RoomNum}】人数：${room.Capacity} 设备：${displays[index]}`,
          value: index,
          RoomID: room.RoomID,
          maxNum: room.Capacity,
        }));
        // 设置数据
        that.setData({ rooms: options });
        console.log('会议室', that.data.rooms);
      },
      fail(err) {
        console.error(err.errMsg);
      },
    });
  },

  change(e) {
    this.setData({ value1: e.detail });
    console.log(e.detail);
  },
  //获取当前时间
  updateCurrentDate: function () {
    const now = new Date();
    const year = now.getFullYear();
    const month = now.getMonth() + 1;
    const date = now.getDate();

    const formattedMonth = month < 10 ? `0${month}` : `${month}`;
    const formattedDate = date < 10 ? `0${date}` : `${date}`;

    const weekdays = [
      '星期日',
      '星期一',
      '星期二',
      '星期三',
      '星期四',
      '星期五',
      '星期六',
    ];
    const startDayIndex = now.getDay();

    // 创建一个新的数组，包含从今天至一周内的星期几名称
    const weekDaysArray = weekdays
      .slice(startDayIndex)
      .concat(weekdays.slice(0, startDayIndex));

    // 创建一个新的数组，包含从今天至一周内的日期
    let dates = [];
    for (let i = 0; i < 7; i++) {
      let day = new Date(now);
      day.setDate(date + i);
      const dayOfMonth = day.getDate();
      const formattedDayOfMonth =
        dayOfMonth < 10 ? `0${dayOfMonth}` : `${dayOfMonth}`;
      dates.push(formattedDayOfMonth);
    }

    // 将日期数组和星期数组组合在一起
    let combinedArray = [];
    for (let i = 0; i < 7; i++) {
      let obj = {
        date: `${formattedMonth}-${dates[i]}`,
        weekday: weekDaysArray[i],
        hasRes: false,
        //calendarIndex[28]初始化全为0
        calendarIndex: Array.from({ length: 28 }, () => 0),
        // indices: [],
        lengthIn: [],
        startIndex: Array.from({ length: 28 }, () => 0),
        UserName: [],
        Theme: []
      };

      combinedArray.push(obj); // 初始化 calendarIndex 属性
    }

    console.log('获取今天起的一周', combinedArray);

    this.setData({
      currentDate: `${formattedMonth}-${formattedDate}`,
      weekDaysArray: combinedArray,
    });
  },
  getTimeSlotIndices(startTime, endTime) {
    const timeSlots = this.data.timeSlots;
    const startHour = parseInt(startTime.split(':')[0], 10);
    const startMinute = parseInt(startTime.split(':')[1], 10);
    const endHour = parseInt(endTime.split(':')[0], 10);
    const endMinute = parseInt(endTime.split(':')[1], 10);

    const indices = [];

    for (let i = 0; i < timeSlots.length; i++) {
      const [hour, minute] = timeSlots[i].split(':').map(Number);
      if (hour > startHour || (hour === startHour && minute >= startMinute)) {
        if (hour < endHour || (hour === endHour && minute <= endMinute)) {
          indices.push(i);
        }
      }
    }
    return indices;
  },
  // 弹出层
  showPopup(e) {
    this.setData({
      formShow: ~this.data.formShow,
      checkedDay: e.currentTarget.dataset.date,
      beginTime: '请选择开始时间',
      endTime: '请选择结束时间',
      inputNumber: null,
    });
    if (this.data.value1 >= 0)
      this.setData({
        room: this.data.rooms[this.data.value1].text.substring(
          0,
          Math.max(this.data.rooms[this.data.value1].text.indexOf('】'), 0) + 1
        ),
      });
    console.log('点击了', this.data.room);
  },
  // 展示数据选择器并判断类型
  showTime: function (e) {
    const type = e.currentTarget.dataset.type;
    this.setData({
      timeType: type,
    });
    console.log('时间选择器', e.currentTarget.dataset.type);
    this.setData({ startShow: ~this.data.startShow });
  },
  // 计算时间对应时间端的下标
  calculateIndex: function (time) {
    const startTime = "08:00";
    const timeDiff = this.getTimeDifference(startTime, time);
    const index = Math.floor(timeDiff / 30);
    return index;
  },
  // 获取时间差（分钟）
  getTimeDifference: function (startTime, endTime) {
    const start = new Date("2024-12-06 " + startTime);
    const end = new Date("2024-12-06 " + endTime);
    const diff = end - start;
    return Math.floor(diff / (1000 * 60));
  },
  //计算是否是合法时间端
  checkTime() {
    const [date1, time1] = this.data.beginTime.split(' ');
    const insex1 = this.calculateIndex(time1);
    const [date2, time2] = this.data.endTime.split(' ');
    const insex2 = this.calculateIndex(time2);
    const arr = this.data.weekDaysArray[this.data.checkClomn].calendarIndex;
    console.log("否是合法时间端", arr.slice(insex1, insex2 + 1).includes(1));
    return arr.slice(insex1, insex2 + 1).includes(1);
  },
  // 获取开始 结束时间
  getStartTime(e) {
    // 获取当前年份以构建完整的日期字符串
    const now = new Date();
    const year = now.getFullYear();
    const selectedTime = e.detail; // 从事件中获取选择的时间
    const index = this.calculateIndex(selectedTime);

    /*获取对应列的下标*/
    // 解析 checkedDay 和 currentDate 成 MM 和 DD
    const [checkedMonth, checkedDate] = this.data.checkedDay.split('-').map(Number);
    const [currentMonth, currentDate] = this.data.currentDate.split('-').map(Number);

    // 创建两个 Date 对象
    const date1 = new Date(year, checkedMonth - 1, checkedDate); // 注意：月份是从0开始计数的
    const date2 = new Date(year, currentMonth - 1, currentDate);

    // 如果 date1 是过去的一年，则将其年份加1
    if (date1 < date2 && date2.getMonth() === 0 && date2.getDate() === 1) {
      date1.setFullYear(date1.getFullYear() + 1);
    }

    // 计算两个日期之间的时间差（以毫秒为单位）
    const timeDiff = Math.abs(date2 - date1);

    // 将时间差转换为天数
    const daysDiff = Math.ceil(timeDiff / (1000 * 60 * 60 * 24));
    this.setData({
      checkClomn: daysDiff
    })
    console.log("相差是时间", index, daysDiff);

    if (this.data.weekDaysArray[daysDiff].calendarIndex[index]) {
      wx.showToast({
        title: '此时间无法选择，请查看合适的时间',
        icon: 'none',
        duration: 2000,
      });
      return;
    }
    else if (this.data.timeType === 'start') {
      // 设置开始时间
      const beginTime = `${year}-${this.data.checkedDay} ${selectedTime}`;
      console.log("设置开始时间", selectedTime);

      //获取当前时间 hh:mm
      let hours = now.getHours(); // 获取当前小时
      let minutes = now.getMinutes(); // 获取当前分钟
      // 确保小时和分钟是两位数
      hours = hours < 10 ? '0' + hours : hours;
      minutes = minutes < 10 ? '0' + minutes : minutes;
      const nowTime = `${hours}:${minutes}`;
      console.log("获取当前时间 hh:mm", nowTime);
      //进行对此 检查开始时间是否大于现实时间
      let [h1, m1] = nowTime.split(':').map(Number);
      let [h2, m2] = selectedTime.split(':').map(Number);
      if (h1 * 60 + m1 - (h2 * 60 + m2) > 0 && this.data.checkedDay.toLowerCase() == this.data.currentDate.toLowerCase()) {
        wx.showToast({
          title: '请选择合适的时间',
          icon: 'none',
          duration: 2000,
        });
        return;
      }
      // 检查开始时间是否小于结束时间
      else if (
        this.data.endTime &&
        new Date(beginTime) >= new Date(this.data.endTime)
      ) {
        wx.showToast({
          title: '开始时间必须小于结束时间',
          icon: 'none',
          duration: 2000,
        });
        return;
      }
      this.setData({ beginTime: beginTime });
      console.log("选择的时间为", this.data.beginTime);
    } else if (this.data.timeType === 'end') {
      // 设置结束时间
      const endTime = `${year}-${this.data.checkedDay} ${selectedTime}`;
      // 检查结束时间是否大于开始时间
      if (
        this.data.beginTime &&
        new Date(endTime) <= new Date(this.data.beginTime)
      ) {
        wx.showToast({
          title: '结束时间必须大于开始时间',
          icon: 'none',
          duration: 2000,
        });
        return;
      }
      this.setData({ endTime: endTime });
      console.log("选择的时间为", this.data.endTime);
    }
    this.setData({ startShow: !this.data.startShow }); // 切换显示状态
  },
  //确定 提交预约
  submitForm() {
    const that = this;
    console.log("15465", this.data.beginTime);
    if (!this.data.isCheckRoom) {
      wx.showToast({
        title: '请先选择会议室',
        icon: 'error',
      });
    } //判断inputNumber为数字！
    else if (!this.data.inputTheme || !this.data.inputNumber || this.data.beginTime == '请选择开始时间' | this.data.endTime == '请选择结束时间') {
      wx.showToast({
        title: '选项不能为空',
        icon: 'error',
      });
    }
    else if (!Number.isInteger(Number(this.data.inputNumber))) {
      wx.showToast({
        title: '人数请输入数字格式',
        icon: 'error',
      });
    } else if (
      this.data.inputNumber > this.data.rooms[this.data.value1].maxNum
    ) {
      wx.showToast({
        title: '人数超过上限',
        icon: 'error',
      });
    } else if (this.checkTime()) {
      wx.showToast({
        title: "时间段选取不合理，请查看后重新选择",
        icon: 'error',
        duration: 1500,
      });
    }
    else {
      const params = {
        WeiXinID: weixinId,
        ReservationID: ' ', //新预约为空，修改预约必填
        Reservation: {
          Theme: this.data.inputTheme,
          BeginTime: this.data.beginTime,
          EndTime: this.data.endTime,
          Nums: this.data.inputNumber,
          RoomID: this.data.rooms[this.data.value1].RoomID,
        }
      };
      console.log("确定 提交预约", params);
      const that = this;
      wx.request({
        //https://itlab.ctgu.edu.cn/labapi
        url:
          'https://itlab.ctgu.edu.cn/labapi/MeetingManage/SaveReservation',
        method: 'POST',
        data: params,
        header: {
          'content-type': 'application/json',
          'Cookie': cookie
        },
        success(res) {
          console.log(res.data);
          if (res.data.status >0) {
            wx.showToast({
              title: '会议预约失败',
              icon: 'error',
            });
          }
          else
            //数据清空
            wx.showToast({
              title: '预约成功',
              icon: 'success',
              duration: 1500,
              mask: false,
              success: function (res) {
                that.setData({
                  beginTime: '请选择开始时间',
                  endTime: '请选择结束时间',
                  inputTheme: '',
                  inputNumber: null,
                });
                // 提示框显示成功的回调函数
                // 使用 setTimeout 来延迟执行页面跳转
                setTimeout(function () {
                  wx.redirectTo({
                    url: '/pages/index/index'
                  });
                }, 1600); // 这里的延迟时间和 duration 应该一致或略长一点以确保提示框完全消失
              }
            });

        },
        fail(err) {
          console.error(err.errMsg);
        },
      });
    }
    that.setData({
      beginTime: '请选择开始时间',
      endTime: '请选择结束时间',
      inputTheme: '',
      inputNumber: null,
    });
  },
  //更新内容
  InputTheme: function (e) {
    console.log(e.detail.value);
    this.setData({
      inputTheme: e.detail.value,
    });
  },
  InputNumber: function (e) {
    console.log(e.detail.value);
    this.setData({
      inputNumber: e.detail.value,
    });
  },
});
